package com.thin.tomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import static java.lang.System.out;

public class ThinTomcat {
	private int port = 8080;

	public ThinTomcat(int port) {
		this.port = port;
	}

	public void start() {
		out.println("================================");
		out.println();
		out.println("          ThinTomcat            ");
		out.println();
		out.println("================================");
		initServletMapping();
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			out.println("ThinTomcat is started on:" + port);
			while (true) {
				Socket socket = serverSocket.accept();
				InputStream inputStream = socket.getInputStream();
				OutputStream outputStream = socket.getOutputStream();
				out.println("=>>>in");
				Request request = new Request(inputStream);
				Response response = new Response(outputStream);
				dispatch(request, response);
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != serverSocket) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void initServletMapping() {
		ServletConfig.addMapping(new ServletMapping("aa", "/test1", "com.thin.tomcat.servlet.Test1Servlet"));
		ServletConfig.addMapping(new ServletMapping("bb", "/test2", "com.thin.tomcat.servlet.Test2Servlet"));
		ServletConfig.addMapping(new ServletMapping("cc", "/", "com.thin.tomcat.servlet.IndexServlet"));
	}

	public void dispatch(Request myRequest, Response myResponse) {
		String clazz = ServletConfig.getClassFullName(myRequest.getUrl());
		// 反射
		try {
			if (clazz == null) {
				myResponse.write404("no mapping for " + myRequest.getUrl());
				return;
			}
			Class<BaseServlet> myServletClass = (Class<BaseServlet>) Class.forName(clazz);
			BaseServlet myServlet = myServletClass.newInstance();
			myServlet.service(myRequest, myResponse);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new ThinTomcat(8088).start();
	}
}
